package com.andox.fn.inf.rpc.rest.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;

import org.apache.commons.lang3.reflect.FieldUtils;

import com.andox.fn.inf.rpc.rest.config.InterfaceConfig;
import com.andox.fn.inf.rpc.rest.config.OverridableProperty;
import com.andox.fn.inf.rpc.rest.config.ReferenceConfig;
import com.andox.fn.inf.rpc.rest.util.ReflectUtil.InstanceMethodCallback;


/**
 * @ClassName: InterfaceConfigUtil
 * @author: Andox
 * @date: 2019年8月23日 下午2:34:53
 * 
 */
public class InterfaceConfigUtil {

	/**
	 * 合并服务端/动态配置端的属性
	 * 
	 * @param rc
	 * @param sc
	 * @return
	 */
	public static ReferenceConfig mergeServiceConfig(ReferenceConfig rc, ReferenceConfig sc) {
		ReflectUtil.doWithInstanceMethods(rc, InterfaceConfig.class, new InstanceMethodCallback() {
			@Override
			public void doWith(Object instance, Method m) {
				String name = m.getName();
				if (!name.startsWith("set") || m.getParameterCount() != 1 || Modifier.isStatic(m.getModifiers()))
					return;
				String field = name.substring(3, 4).toLowerCase() + name.substring(4);
				Field f = FieldUtils.getField(ReferenceConfig.class, field, true);
				if (f != null) {
					OverridableProperty op = f.getAnnotation(OverridableProperty.class);
					if (op != null && propertyCanOverridable(op)) {
						try {
							m.invoke(rc, f.get(sc));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		});

		return rc;
	}

	static boolean propertyCanOverridable(OverridableProperty op) {
		return Stream.of(op.value()).filter(e -> {
			return e.equals(OverridableProperty.OVERRIDE_FROM_PROVIDER_SIDE)
					|| e.equals(OverridableProperty.OVERRIDE_FROM_PROVIDER_SIDE);
		}).findAny().isPresent();
	}
}
